package com.zr.sms.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.zr.sms.model.Employee;
import com.zr.sms.model.Shoplist;
import com.zr.sms.service.UpdateService;
import com.zr.sms.serviceimpl.UpdateServiceImpl;

public class UpdateOrderServlet extends HttpServlet{
	UpdateService update=new UpdateServiceImpl();
	
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	   doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		  resp.setCharacterEncoding("utf-8");
		  String gnumberss=req.getParameter("gnumbers");
		  Shoplist s=(Shoplist) req.getSession().getAttribute("shoplist");//从session中获取购物清单对象
		  String scontent=s.getScontent();
		  JSONObject obj =JSONObject.fromObject(scontent);//获取购物清单内容的json对象
		  String gss=obj.getString("gids");
		  String []gs=gss.split(",");
		  String gnumberss1=obj.getString("gnumbers");  
		  obj.put("gnumbers", gnumberss);
		  
		  String gpricess=obj.getString("gprices");
		  String[]gprices=gpricess.split(",");//获取单价的字符串数组
		  String []numbers=gnumberss.split(",");//购买数量的字符串数组
		  String[]numbers1=gnumberss1.split(",");
		  int[] numbers2=new int[numbers.length];
		  for (int i = 0; i < numbers2.length; i++) {
			numbers2[i]=Integer.parseInt(numbers[i])-Integer.parseInt(numbers1[i]);
			
		}
		  for (int i = 0; i < numbers2.length; i++) {
				update.updataGoods(Integer.parseInt(gs[i]),numbers2[i]);
		   	}
			  
		  double nowtotal=0;
		  for (int i = 0; i < numbers.length; i++) {
			nowtotal=nowtotal+(Integer.parseInt(numbers[i])*Double.parseDouble(gprices[i]));
			//获取退款后的 总金额
		}
		  double chajia=s.getStotalmoney()-nowtotal;
		  
		  Employee emp=(Employee) req.getSession().getAttribute("currentemp");
		  int cid=emp.getCid();//获取当前收银员的柜台
		  update.cutMoney(chajia, cid);//减掉了柜台里的钱
		  update.uodateScontentBySid(obj.toString(),nowtotal,s.getSid());//更新购物清单内容最终买了多少件什么商品
		  PrintWriter out=resp.getWriter();
		  JSONObject jsobj=new JSONObject();
		  jsobj.put("nowtotal", nowtotal);
		  jsobj.put("chajia", chajia);
		  jsobj.put("msg", "购物清单更新成功");
		  out.write(jsobj.toString());
		
		
	}

}
